/*
 * File:    Base64.java
 * Created: 19-Feb-2009
 * Version: $Id$
 *
 * COPYRIGHT (C) 2009, Bitgate Mobile, LLC.  All Rights Reserved.
 *
 * software@bitgatemobile.com
 */

package com.webplasm.render.tags.u;

import java.util.Arrays;
import java.util.List;

import com.webplasm.context.RenderContext;
import com.webplasm.render.engine.RenderException;
import com.webplasm.render.tags.TagInterface;
import com.webplasm.render.tags.WrappedNode;

/**
 * This tag allows for encoding or decoding in Base64 format.
 * 
 * @author kenji
 * @since Webplasm 1.0
 */
public class Base64 extends WrappedNode implements TagInterface {
	private static final String DESCRIPTION = "Encodes or decodes data in Base64 encoding.";
	
	private static final String BASE64_ACTION_ENCODE = "encode";
	private static final String BASE64_ACTION_DECODE = "decode";

	public String getNamespace() {
		return "u";
	}
	
	public List<String> getAttributes() {
		return Arrays.asList("action");
	}
	
	public List<String> getManagedNodes() {
		return null;
	}

	public String getDescription() {
		return DESCRIPTION;
	}

	@Override
	public StringBuffer render(RenderContext rContext) throws RenderException {
		if (elements.get("action") == null) {
			throw new RenderException("u:base64 requires an action to be set to 'encode' or 'decode'");
		}
		
		String base64Action = elements.get("action").toLowerCase();
		
		if (base64Action.equals(BASE64_ACTION_ENCODE)) {
			try {
				return new StringBuffer(com.bitgate.util.encoder.Base64.encodeString(super.render(rContext).toString()));
			} catch(IllegalArgumentException ex) {
				throw new RenderException("Unable to encode data: " + ex.getMessage());
			}
		} else if (base64Action.equals(BASE64_ACTION_DECODE)) {
			try {
				return new StringBuffer(com.bitgate.util.encoder.Base64.decodeString(super.render(rContext).toString()));
			} catch(IllegalArgumentException ex) {
				throw new RenderException("Unable to decode data: " + ex.getMessage());
			}
		}
		
		throw new RenderException("u:base64 requires action to be set to 'encode' or 'decode'");
	}
}